﻿using System;
using System.Globalization;

// ReSharper disable once CheckNamespace
namespace DotNet.Utilities
{
    public static class ValueConverter
    {
        public static T Parse<T>(string s, T failedValue = default(T), bool rethrow = false) where T : IConvertible
        {
            var result = failedValue;
            if (string.IsNullOrWhiteSpace(s) && !rethrow)
                return result;

            try
            {
                var convertible = (IConvertible)s;
                if (convertible != null)
                {
                    var typeObj = convertible.ToType(typeof(T), CultureInfo.InvariantCulture);
                    result = (T)typeObj;
                }
            }
            catch
            {
                if (rethrow)
                {
                    throw;
                }
            }

            return result;
        }
    }
}
